<template>
  <div>
    <header>
      <div class="logo-container">
        <h1>
          <img src="../../images/logo.jpg" alt="" @click="goHome">
        </h1>
        <h3>欢迎登录</h3>
        <div class="home">
          <div class="enter-home" @click="goHome">
            进入网站首页
            <span class="icon-one">
              <el-icon color="#27ba9b"><ArrowRight /></el-icon>
            </span>
            <span class="icon-two">
              <el-icon><ArrowRight /></el-icon>
            </span>
          </div>
        </div>
      </div>
    </header>
    <section>
      <div class="container">
        <div class="form-wrapper">
          <el-form
            ref="form"
            :rules="rules"
            :model="params"
          >
            <template v-if="mode === 'account'">
              <el-button @click="useMessage" class="btn">
                使用短信登录
              </el-button>
              <el-form-item prop="account">
                <el-input
                  v-model="params.account"
                >
                  <template #prepend>
                    <i-ep-user class="icon" />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                  v-model="params.password"
                  type="password"
                >
                  <template #prepend>
                    <i-ep-lock class="icon" />
                  </template>
                </el-input>
              </el-form-item>
            </template>
            <template v-else>
              <el-button @click="useAccount" class="btn">
                使用账号登录
              </el-button>
              <el-form-item prop="mobile">
                <el-input
                  v-model="params.mobile"
                >
                  <template #prepend>
                    <i-ep-user class="icon" :size="24" />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="code">
                <el-input
                  v-model="params.code"
                >
                  <template #prepend>
                    <icon name="dun-pai" :size="24 * .9" color="#fff" />
                  </template>
                  <template #append>
                    <el-button
                      @click="sendCode"
                      :disabled="countDown !== CODE_WAIT_TIME"
                    >
                      {{ countDown === CODE_WAIT_TIME ? '发送验证码' : countDown }}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </template>
            <el-form-item>
              <el-checkbox
                v-model="params.isMemo"
                label="记住我"
              />
            </el-form-item>
            <el-form-item prop="isAgree">
              <el-checkbox v-model="params.isAgree">
                我已同意
                <a href="">《隐私条款》</a>
                和
                <a href="">《服务条款》</a>
              </el-checkbox>
            </el-form-item>
            <el-button
              type="primary"
              :disabled="!params.isAgree"
              @click="() => mode === 'account' ? onLoginWithAccount() : onLoginWithCode()"
            >
              登录
            </el-button>
          </el-form>
        </div>
      </div>
    </section>
    <footer>
      <div class="footer-container">
        <div>
          <div class="statement">
            <span>关于我们</span>
            <span>|</span>
            <span>帮助中心</span>
            <span>|</span>
            <span>售后服务</span>
            <span>|</span>
            <span>配送和验收</span>
            <span>|</span>
            <span>商务合作</span>
            <span>|</span>
            <span>搜索推荐</span>
            <span>|</span>
            <span>友情链接</span>
            <!-- <icon name="珍珠奶茶" size="100" /> -->
          </div>
          <div class="copyright">
            CopyRight©小兔鲜儿
          </div>
        </div>
      </div>
    </footer>
    <div>Mouse position is at: {{ x }}, {{ y }}</div>
  </div>
</template>

<script setup name="login">
import { useStore } from 'vuex';
import { CODE_WAIT_TIME } from '@/constants';
import { throttle } from 'lodash';
import * as useApi from '@/api/user';
import * as strategy from '@/constants/strategy';
import { useRouter, useRoute } from 'vue-router';
// 引入hooks文件
import { useMouse } from './hooks.js';
const { x, y } = useMouse();

const router = useRouter();
const route = useRoute();

const store = useStore();

const mode = ref('account'); // 'account' | 'message'
const countDown = ref(CODE_WAIT_TIME);

const form = ref(null);

const account = localStorage.getItem('account') || '';
const password = localStorage.getItem('password') || '';
const mobile = localStorage.getItem('mobile') || '';
const isMemo = localStorage.getItem('isMemo') === 'true' || true;
const userColor = ref(true);

const params = reactive({
  account: isMemo ? account : '',
  password: isMemo ? password : '',
  mobile: isMemo ? mobile : '',
  code: '',
  isMemo,
  isAgree: false,
});

function accountChecker(_, value, cb) {
  if (!strategy.ACCOUNT.test(value.trim())) {
    cb(new Error('账号格式错误 应为字母开头 共6-20个字符'));
  } else {
    cb();
  }
}

function mobileChecker(_, value, cb) {
  if (!strategy.MOBILE.test(value.trim())) {
    cb(new Error('手机号格式错误'));
  } else {
    cb();
  }
}

function codeChecker(_, value, cb) {
  if (!strategy.CODE.test(value.trim())) {
    cb(new Error('验证码格式错误'));
  } else {
    cb();
  }
}

function agreeChecker(_, value, cb) {
  if (!value) {
    cb(new Error('不同意不行'));
  } else {
    cb();
  }
}
function codeLogin() {
  codeColor.value = true;
  userColor.value = false;
}
function userLogin() {
  userColor.value = true;
  codeColor.value = false;
}

const rules = reactive({
  account: [{ validator: accountChecker, trigger: 'blur' }],
  mobile: [{ validator: mobileChecker, trigger: 'blur' }],
  code: [{ validator: codeChecker, trigger: 'blur' }],
  isAgree: [{ validator: agreeChecker, trigger: 'change' }],
});

function onLoginWithAccount() {
  form.value.validate(async (valid) => {
    if (valid) {
      const res = await store.dispatch('user/login', params);

      if (res.success) {
        // 如果勾选了记住我 就记录相关数据
        if (params.isMemo) {
          localStorage.setItem('account', params.account);
          localStorage.setItem('password', params.password);
          localStorage.setItem('isMemo', params.isMemo);
        }
      } else {
        // 失败了清空密码
        params.password = '';
      }
      router.push('/home');
    } else {
      return false;
    }
  });
}


// 发送验证码
const sendCodeWithCheckSuccess = throttle(() => {
  let timer = null;
  useApi.loginWithCode(params.mobile)
    .then((msg) => {
      ElMessage({
        message: msg,
        type: 'success',
      });
    })
    .catch((msg) => {
      sendCodeWithCheckSuccess.cancel();
      clearInterval(timer);
      countDown.value = CODE_WAIT_TIME;
      ElMessage({
        message: msg,
        type: 'error',
      });
    });
  countDown.value = CODE_WAIT_TIME - 1;
  timer = setInterval(() => {
    countDown.value--;
    if (countDown.value < 1) {
      clearInterval(timer);
      countDown.value = CODE_WAIT_TIME;
    }
  }, 1000);
}, CODE_WAIT_TIME * 1000);

function sendCode() {
  if (!strategy.MOBILE.test(params.mobile)) {
    return;
  }
  // 成功
  sendCodeWithCheckSuccess();
}
function useMessage() {
  mode.value = 'message';
}
function useAccount() {
  mode.value = 'account';
}
</script>


<style lang="scss" scoped>
header{
  height: 132px;
  width: 100%;
  .logo-container{
    margin: 0 auto;
    width: 1240px;
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    h1{
      img{
        height: 132px;
        cursor: pointer;
      }
    }
    h3{
      flex: 1;
      margin: 0 0 38px 20px;
      font-size: 28px;
      color: #666666;
      font-weight: 400;
    }
    .home{
      display: flex;
      align-items: center;
      margin-bottom: 38px;
      font-size: 18px;
      cursor: pointer;
      .enter-home{
        position: relative;
        .icon-one{
          position: absolute;
          color: #27ba9b;
          top: 3px;
          right: -20px;
        }
        .icon-two{
          position: absolute;
          color: #27ba9b;
          top: 3px;
          right: -30px;
        }
      }
    }
  }
}
section{
  margin-top: 40px;
  height: 488px;
  background: url(../../images/summer.jpg);
  position: relative;
  .container {
    padding: 16px 16px;
    width: 380px;
    // height: 400px;
    background-color: #fff;
    position: absolute;
    top: 54px;
    left: 50%;
    transform: translateX(220px);
    .form-wrapper

      :deep(.el-input-group__prepend) {
        background-color: #cfcdcd;
        padding: 8px;
      }

      .icon {
        font-size: 18px;
        color: white;
      }
      .btn {
        margin: 16px 0;
        color: #27ba9b;
      }
    }
  }

footer{
  padding: 30px 0 50px 0;
  .footer-container{
    text-align: center;
    color: #999999;
    .statement{
      padding-top: 20px;
      span{
        padding: 0 8px;
      }
    }
    .copyright{
      padding-top: 20px;
    }
  }
}
</style>
